package main

import (
	"encoding/json"
	"fmt"
	"time"
)

type Order struct {
	ID         int       `json:"id"`
	Title      string    `json:"title"`
	CreateTime time.Time `json:"create_time"`
}

const layout = "2006年01月02日 15时04分05秒"

func (o *Order) MarshalJSON() ([]byte, error) {
	type TempOrder Order // 定义新类型

	return json.Marshal(struct {
		CreateTime string `json:"create_time"`
		*TempOrder
	}{
		CreateTime: o.CreateTime.Format(layout),
		TempOrder:  (*TempOrder)(o),
	})
}

func (o *Order) UnmarshalJSON(data []byte) error {
	type TempOrder Order
	ot := struct {
		CreateTime string `json:"create_time"`
		*TempOrder
	}{
		TempOrder: (*TempOrder)(o),
	}

	if err := json.Unmarshal(data, &ot); err != nil {
		return err
	}
	var err error
	o.CreateTime, err = time.Parse(layout, ot.CreateTime)
	if err != nil {
		return err
	}

	return nil
}

func main() {

	o1 := Order{
		ID:         1111,
		Title:      "666",
		CreateTime: time.Now(),
	}

	b, err := json.Marshal(&o1)
	if err != nil {
		fmt.Println("json marshal failed,err:", err)
	}

	fmt.Printf("%s\n", b)
	var o2 Order
	jsonStr := `{"create_time":"2022年05月13日 10时19分19秒","id":11111,"title":"哈哈哈"}`
	err = json.Unmarshal([]byte(jsonStr), &o2)
	if err != nil {
		fmt.Println("json unmarshal failed, err:", err)
	}

	fmt.Printf("%#v\n", o2)

}
